<?php 

class Application_Model_tkqwMD
{
//		$tkqwMD = new Application_Model_tkqwMD();
/*		
		Zend_Debug::dump($tkqwMD->curlCatalog());
		$tkqwMD->add();
		$tkqwMD->curlCoverImgs();
*/

/*
	$ch = curl_init("http://demowarehouse.tecknoquest.com/retailers/LLBr/COVERS/dem001.jpg");
	$fp = fopen("dem001.jpg", "w");
	
	curl_setopt($ch, CURLOPT_HEADER, FALSE);
	curl_setopt($ch, CURLOPT_FILE, $fp);
	curl_setopt($ch, CURLOPT_USERPWD, 'LLBr:lailai1');
	curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);   
	
	if(curl_exec($ch) === false)
	{
	    echo 'Curl error message: ' . curl_error($ch);
	}
	
	curl_close($ch);
	fclose($fp);
*/
		
/*
	$ary_coverFNames = array(
	    'emc2734.jpg',
	    'emc3705.jpg',
		'emc3706.jpg'
	);
	$url = 'http://demowarehouse.tecknoquest.com/retailers/LLBr/COVERS/';
	$mh = curl_multi_init();

	$coversAmt = count($ary_coverFNames);
	$ary_chs = array();
	$ary_fps = array();
	for($i = 0; $i < $coversAmt; $i++)
	{
		$coverFName = $ary_coverFNames[$i];
		$ary_fps[$i] = fopen($ary_coverFNames[$i], "w");
		//批量初始化curl资源
		$ary_chs[$i] = curl_init($url . $coverFName);
		curl_setopt($ary_chs[$i], CURLOPT_HEADER , FALSE);
		curl_setopt($ary_chs[$i], CURLOPT_FILE, $ary_fps[$i]);
		curl_setopt($ary_chs[$i], CURLOPT_USERPWD, 'LLBr:lailai1');
		curl_setopt($ary_chs[$i], CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
		curl_setopt($ary_chs[$i], CURLOPT_CONNECTTIMEOUT, 60);   
		//批量增加句柄
		curl_multi_add_handle($mh, $ary_chs[$i]);
	}

	$running = null;
	do{
		$mrc = curl_multi_exec($mh, $running);
	}while($running);

     
	for($i = 0; $i < $coversAmt; $i++)
	{
		echo 'Curl error message (' . $i . '): ' . curl_error($ary_chs[$i]) . '<br/>';
		curl_multi_remove_handle($mh, $ary_chs[$i]);
		curl_close($ary_chs[$i]);
		fclose($ary_fps[$i]);
	}

	curl_multi_close($mh);
	echo 'Finished';
*/	
	
	private $DBTable_tkqw;
	private $catalogFName;	//TKQW書籍清單的檔名。
	private $pathToSave;	//儲存和TKQW相關資料的資料夾名稱。
	private $dirNameToSaveCoverImg;	//儲存封面圖片的資料夾名稱。
	private $serverUrl;		//TKQW伺服器位置。
	private $catalogUrl;		//TKQW書籍清單位置。
	private $coverUrl;		//TKQW封面圖片位置。
	
	public function __construct()
	{
		$this->DBTable_tkqw = new Zend_Db_Table('tkqw');
		$this->catalogFName = 'catalog_v2.txt';
		$this->serverUrl = 'http://demowarehouse.tecknoquest.com/retailers/LLBr/';
		$this->catalogUrl = $this->serverUrl . 'DATA/catalog_v2.txt';
		$this->converUrl = $this->serverUrl . 'COVERS/';
		
		//如果還未建立資料夾"tkqw"，就建立它吧！
		$this->pathToSave = 'tkqw';
		if(FALSE === is_dir($this->pathToSave))
		{
			mkdir($this->pathToSave);
		}
		
		//如果還未建立資料夾"tkqw/cover"，就建立它吧！
		$this->dirNameToSaveCoverImg = 'cover';
		if(FALSE === is_dir($this->pathToSave . '/' . $this->dirNameToSaveCoverImg))
		{
			mkdir($this->pathToSave . '/' . $this->dirNameToSaveCoverImg);
		}
	}
	
	
	
	
	
	/**
	 * 到TKQW伺服器取得書籍清單，並儲存到資料夾"tkqw"底下。
	 * @param none
	 *
	 * @return $ary_rsp['isSuccess'] 是否成功取得書籍清單？
	 * @return $ary_rsp['errMsg'] 錯誤訊息，如果無錯誤，預設為空字串。
	 */
	public function curlCatalog()
	{
		$ch = curl_init($this->catalogUrl);
		$fp = fopen($this->pathToSave . '/' . $this->catalogFName, 'w');
		
		curl_setopt($ch, CURLOPT_HEADER, FALSE);
		curl_setopt($ch, CURLOPT_FILE, $fp);
		curl_setopt($ch, CURLOPT_USERPWD, 'LLBr:lailai1');
		curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);   
		
		$isSuccess = curl_exec($ch);
		
		if(FALSE === $isSuccess)
		{
		    $ary_rsp['isSuccess'] = FALSE;
			$ary_rsp['errMsg'] = curl_error($ch);
		}
		elseif(TRUE === $isSuccess)
		{
			$ary_rsp['isSuccess'] = TRUE;
			$ary_rsp['errMsg'] = '';
		}
		
		curl_close($ch);
		fclose($fp);
		
		return $ary_rsp;
	}
	

	
	
	
	/**
	 * 到TKQW伺服器取得封面圖片，並儲存到資料夾"tkqw/cover"底下。
	 * @param none
	 * 
	 * @return none
	 */
	public function curlCoverImgs()
	{
		$DBRowSet_tkqw = $this->DBTable_tkqw->fetchAll();
		$coversAmt = count($DBRowSet_tkqw);
		$url = $this->converUrl;
		$ary_chs = array();
		$ary_fps = array();
		$cnt = 0;
		$mh = curl_multi_init();
		foreach($DBRowSet_tkqw as $eachElem)
		{
			$ary_fps[$cnt] = fopen(
			$this->pathToSave
			. '/'
			. $this->dirNameToSaveCoverImg
			. '/'
			. $eachElem->tkqw_COVER_FNAME, "w");
			$ary_chs[$cnt] = curl_init($url . $eachElem->tkqw_COVER_FNAME);
			curl_setopt($ary_chs[$cnt], CURLOPT_HEADER , FALSE);
			curl_setopt($ary_chs[$cnt], CURLOPT_FILE, $ary_fps[$cnt]);
			curl_setopt($ary_chs[$cnt], CURLOPT_USERPWD, 'LLBr:lailai1');
			curl_setopt($ary_chs[$cnt], CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
			curl_setopt($ary_chs[$cnt], CURLOPT_CONNECTTIMEOUT, 60);   
			curl_multi_add_handle($mh, $ary_chs[$cnt]);
			$cnt++;
		}
	
		$isRunning = NULL;
		do{
			curl_multi_exec($mh, $isRunning);
		}while($isRunning);
	     
		for($i = 0; $i < $coversAmt; $i++)
		{
			curl_multi_remove_handle($mh, $ary_chs[$i]);
			curl_close($ary_chs[$i]);
			fclose($ary_fps[$i]);
		}
		curl_multi_close($mh);
	}
	
	
	
	
	
	/**
	 * 剖析圖書目錄(Tab分隔的文字檔)，並寫入資料表`tkqw`內。
	 * @param none
	 * 
	 * @return none
	 */
	public function add()
	{
		$cnt = 0;
		$ary_schema = array();
		$ary_tkqw = array();
		$fp = @fopen($this->pathToSave . '/' . $this->catalogFName, "r");
		if($fp)
		{
		    while (($buffer = fgets($fp)) !== FALSE)
		    {
				$cnt++;
		        $ary_buffer = explode("\t", $buffer);
		        if(1 === $cnt)
		        {
			        foreach($ary_buffer as $eachElem)
			        {
			        	$ary_schema[] = trim($eachElem);
			        }
		        }
		        elseif($cnt > 1)
		        {
		        	foreach($ary_buffer as $index => $eachElem)
		        	{
		        		$ary_tkqw[$this->DBTable_tkqw->info('name') . '_' . $ary_schema[$index]] = trim($eachElem);
		        	}
//Zend_Debug::dump($ary_tkqw);
					$ary_addData['tkqw_status'] = 1; 
		        	$ary_tkqw['tkqw_addDT'] = Zend_Date::now()->toString('YYYY-MM-dd HH:mm:ss');
		        	$this->DBTable_tkqw->insert($ary_tkqw);
		        	echo "<br/><br/><br/><br/>";
		        }
		    }
		    if(!feof($fp))
		    {
		        echo "Error: unexpected fgets() fail\n";
		    }
		    fclose($fp);
		}
	}
}